using Gateway.Common.Enums;
using Gateway.IQuery.User.Result;
using Gateway.IQuery.UserMessage;
using Gateway.IQuery.UserMessage.Result;
using Gateway.IRepositories;

namespace Gateway.Query;

/// <summary>
/// user message query
/// </summary>
public class UserMessageQuery : IUserMessageQuery
{
    private readonly IQueryRepository _repository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="repository"></param>
    public UserMessageQuery(IQueryRepository repository)
    {
        _repository = repository;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="account"></param>
    /// <param name="size"></param>
    /// <returns></returns>
    public async Task<List<UserMessageDetailResult>> GetAllNoRead(string account, int size)
    {
        List<UserMessageDetailResult> data;
        if (size > 0)
        {
             data = await _repository.Db.Queryable<UserMessageDetailResult>().Where(x =>
                    x.Account.Equals(account) && x.ReadStatus == (BooleanStatusEnum.No.Value))
                 .OrderByDescending(x=>x.CreatedTime)
                .Take(size).ToListAsync();
        }
        else
        {
            data = await _repository.Db.Queryable<UserMessageDetailResult>().Where(x =>
                    x.Account.Equals(account) && x.ReadStatus == (BooleanStatusEnum.No.Value))
                .OrderByDescending(x=>x.CreatedTime)
                .ToListAsync();
        }

        UserDetailResult user = null;
        if (data.Count > 0)
        {
            user = await _repository.FindAsync<UserDetailResult>(x => x.UserId.Equals(account));
        }

        foreach (var userMessageDetailResult in data)
        {
            userMessageDetailResult.BuildUser(user);
        }

        return data;
    }
}